package com.kanqiubao.kq.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.kanqiubao.kq.ThisAppApplication;
import com.kanqiubao.kq.activity.BaseActivity;
import com.kanqiubao.kq.http.HttpUrls;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppConfig {
    public static final String[] mAdvertLink = new String[]{"com.app.ad.SplashActivity", "com.app.ad.InterstitialADActivity"
            , "com.app.ad.NativeActivity", "com.app.ad.BannerActivity", "com.app.ad.RewardVideoADActivity", "com.app.ad.FullscreenVideoADActivity"};
    public static String mCopy = "";
    public static String splashid = "9011721882442372";
    public static String bannerid = "2011725862648664";
    public static String initrid = "9031622852741422";
    public static String rewid = "6031821832847318";
    //    public static String videoid = "9031720892749405";//贴片
    public static String videoid = "4071231427025977";//动态
    //    public static String videoid = "9071427852458122";//动态图视频
    public static String tpid = "2071427883300040";//贴片-平台,图

    //    public static String tpid = "6071836467569021";//贴片-平台
//
    public static int getScreenWidth() {
        return ThisAppApplication.getInstance().getResources().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight() {
        return ThisAppApplication.getInstance().getResources().getDisplayMetrics().heightPixels;

    }

    public static float getScreenDensityDpi() {
        return ThisAppApplication.getInstance().getResources().getDisplayMetrics().density;

    }

    public static String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;

    }

    public static String getNowTimeFormat(String timetype) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat(timetype);
        String time = format.format(date);
        return time;

    }

    public static String getNowTime(String fm) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat(fm);
        String time = format.format(date);
        return time;

    }

    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    public static String timeAgo(String time, String format) {

        if (StringUtil.isEmptyString(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        if (StringUtil.isEmptyString(time)) {
            return "";
        }
        SimpleDateFormat sdf;
        if (time.length() <= 19) {
            sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        } else {
            sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        }
        Date da;
        try {
            da = sdf.parse(time);
            long timeStamp = da.getTime();
            Date currentTime = new Date();
            long currentTimeStamp = currentTime.getTime();
            long seconds = (currentTimeStamp - timeStamp) / 1000;

            long minutes = Math.abs(seconds / 60);
            long hours = Math.abs(minutes / 60);
            long days = Math.abs(hours / 24);

            if (seconds <= 15) {
                return "刚刚";
            } else if (seconds < 60) {
                return seconds + "秒前";
            } else if (seconds < 120) {
                return "1分钟前";
            } else if (minutes < 60) {
                return minutes + "分钟前";
            } else if (minutes < 120) {
                return "1小时前";
            } else if (hours < 24) {
                return hours + "小时前";
            } else if (hours < 24 * 2) {
                return "1天前";
            } else if (days < 30) {
                return days + "天前";
            } else {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                String dateString = formatter.format(da);
                return dateString;
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 把GMT标准时间转化自己格式化的时间
     *
     * @param time时间字符串
     * @param format格式化的样式
     * @return
     */
    public static String getFormatTime(String time, String format) {

        if (StringUtil.isEmptyString(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        if (StringUtil.isEmptyString(time)) {
            return "";
        }
        try {
            SimpleDateFormat sdf;
            if (time.length() <= 19) {
                sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            } else {
                sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
            }
            SimpleDateFormat sdfT = new SimpleDateFormat(format);
            Date da = sdf.parse(time);
            return sdfT.format(da);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Date getFormatDate(String time) {
        if (StringUtil.isEmptyString(time)) {
            return null;
        }
        try {
            SimpleDateFormat sdf;
            if (time.length() <= 19) {
                sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            } else {
                sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
            }
            Date da = sdf.parse(time);
            return da;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getFormatTime1(String time, String format) {

        if (StringUtil.isEmptyString(time)) {
            return "";
        }
        try {
            SimpleDateFormat sdfT = new SimpleDateFormat(format);
            Date da = sdfT.parse(time);
            return sdfT.format(da);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static long getFormatTimeMillis(String time, String format) {

        if (StringUtil.isEmptyString(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        if (StringUtil.isEmptyString(time)) {
            return 0;
        }
        try {
            SimpleDateFormat sdf = null;
            if (time.contains("T")) {
                if (time.length() <= 19) {
                    sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                } else {
                    sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
                }
            } else {
                sdf = new SimpleDateFormat(format);
            }
            Date da = sdf.parse(time);
            return da.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getLongTime(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(d);
    }

    public static String getLongTime(long time, String format) {
        Date d = new Date(time * 1000);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(d);
    }

    public static long getNowTimeMillis() {
        return System.currentTimeMillis();
    }

    public static NotificationManager mNotificationManager;

    public static NotificationManager initNotificationManager(Context context) {
        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return mNotificationManager;
    }

    /**
     * 获取版本号
     * <p>
     * param context return
     */
    public static String getVersionName() {
        PackageManager localPackageManager = ThisAppApplication.getInstance().getPackageManager();
        String str = "";
        try {
            PackageInfo localPackageInfo = localPackageManager.getPackageInfo(
                    ThisAppApplication.getInstance().getPackageName(), 0);

            if (localPackageInfo != null)
                str = localPackageInfo.versionName;

        } catch (PackageManager.NameNotFoundException localNameNotFoundException) {
            localNameNotFoundException.printStackTrace();
        }
        return str;
    }

    public static void setJpushAliasAndTags() {
        // Set<String> set = null;
        // if (!StringUtil.isEmptyString(type)) {
        // final String tag2 = "V";// 组
        // set = new HashSet<String>();
        // set.add(tag2);
        // }
        // if (strings != null) {
        // set.addAll(Arrays.asList(strings));
        // }
        // final String alias = SharedPreferencesUtil.getInstance().getUserId();
        // // 别名
        // JPushInterface.setAliasAndTags(ThisAppApplication.getInstance(),
        // alias, null, new TagAliasCallback() {
        //
        // @Override
        // public void gotResult(int arg0, String arg1, Set<String> arg2) {
        // // DebugUntil.createInstance().toastStr("注册成功");
        // System.out.println("====");
        // }
        // });
    }

    //
    // public static void registerDevice() {
    // DeviceRegisteRequestBean bean = new DeviceRegisteRequestBean();
    // bean.setAlias(SharedPreferencesUtil.getInstance().getUserId());
    // bean.setDeviceType("Android");
    // bean.setIMEI(AppConfig.getImei());
    // bean.setTag("");
    // HttpRequestTool<BaseModel> ht = new HttpRequestTool<BaseModel>();
    // ht.setBodyData(bean);
    // ht.cloneRequest(Method.POST, HttpUrls.mDevice, null, "device", "device");
    // }

    public static String getImei() {
        String Imei = "";
        try {
            Imei = ((TelephonyManager) ThisAppApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE))
                    .getDeviceId();
        } catch (Exception e) {
        }
        if (!StringUtil.isEmptyString(Imei)) {
            return Imei;
        } else {
            Imei = Settings.Secure.getString(ThisAppApplication.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);
            if (!StringUtil.isEmptyString(Imei)) {
                return Imei;
            }
        }
        //如果还是为空
        return getUniquePsuedoID();
    }

    //获得独一无二的Psuedo ID
    public static String getUniquePsuedoID() {
        String serial;
        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    public static String getCache() {
        return ThisAppApplication.getInstance().getCacheDir().getAbsolutePath()
                + ThisAppApplication.getInstance().getCacheDir().separator;
    }

    /**
     * 获取缓存路径
     *
     * @param context
     * @return
     */
    public static String getDiskCacheDir() {

        File filew = new File(getCache());
        if (!filew.exists()) {
            filew.mkdirs();
        }
        return filew.toString();
    }

    /**
     * 替换相对路劲的图片
     *
     * @param content
     */
    public static String getStringToImg(String content) {
        if (StringUtil.isEmptyString(content)) {
            return "";
        }
        String regEx = "(<img[^>]+src=\")(\\S+)\""; //
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(content);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String imgUrl = matcher.group(2);
            String temp = "";
//			if (!StringUtil.isEmptyString(imgUrl) && (imgUrl.contains("http://") || imgUrl.contains("https://"))) {
//				// 是全局路劲
//				temp = imgUrl;
//			} else {
//				// 相对路劲
//				temp = AppConfig.ImageUrl(imgUrl);
//			}
            temp = AppConfig.ImageUrl(imgUrl);
            matcher.appendReplacement(result, matcher.group(1) + temp + "\" onClick=\"javascript:imgclick.onImageClick('"
                    + temp + "')\"");
            // mZxDetailPicture.add(temp);
        }
        matcher.appendTail(result);
        return result.toString();
    }

    // public static String replaceHtml(String content){
    //
    // }

    /**
     * 资讯详细图片自适应屏幕
     *
     * @param content
     * @return
     */
    public static String webViewImgAuto(String content) {
        return "<html><head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, " +
                "user-scalable=no\"/><style type='text/css'>img{width:100% !important;height:auto !important}\nbody,div,td,th{font-size:0.95em;" +
                "line-height:1" +
                ".3em;}</style>"
                + "</head><body>" + content + "</body></html>";
    }

    public static String webViewAddJavaScript() {
        String temp = "<script type=\"text/javascript\">" + " function load_night(){"
                + "document.body.style.backgroundColor='#222222';" + "document.body.style.opacity ='0.5';"
                + "var spans=document.getElementsByTagName('span');" + "for(var i=0;i<spans.length;i++){"
                + "spans[i].style.color='#7F7E7E';}" + "var strongs=document.getElementsByTagName('strong');"
                + "for(var i=0;i<strongs.length;i++){" + "strongs[i].firstChild.style.color='#7F7E7E';}}"
                + "function load_day(){" + "document.body.style.backgroundColor='#ffffff';"
                + "document.body.style.opacity ='1';" + "var spans=document.getElementsByTagName('span');"
                + "for(var i=0;i<spans.length;i++){" + "spans[i].style.color='#3D3D3D';}"
                + "var strongs=document.getElementsByTagName('strong');" + "for(var i=0;i<strongs.length;i++){"
                + "strongs[i].firstChild.style.color='#3D3D3D';}}" + " function textsize(size){"
                + "var ps=document.getElementsByTagName('span');" + "for(var i=0;i<ps.length;i++){"
                + "ps[i].style.fontSize=size+'px';ps[i].style.lineHeight=size+'px'" + "}}</script>";
        return temp;
        // <script type="text/javascript">
        //
        // function load_night(){
        // document.body.style.backgroundColor='#000000';
        // var spans=document.getElementsByTagName('span');
        // for(var i=0;i<spans.length;i++){
        // spans[i].style.color='#ffffff';
        // }
        // var strongs=document.getElementsByTagName('strong');
        // for(var i=0;i<strongs.length;i++){
        // strongs[i].firstChild.style.color='#ffffff';
        // }
        // }
        //
        // function load_day(){
        // document.body.style.backgroundColor='#ffffff';
        // var spans=document.getElementsByTagName('span');
        // for(var i=0;i<spans.length;i++){
        // spans[i].style.color='#000000';
        // }
        // var strongs=document.getElementsByTagName('strong');
        // for(var i=0;i<strongs.length;i++){
        // strongs[i].firstChild.style.color='#000000';
        // }
        // }
        //
        // function textsize(size){
        // var ps=document.getElementsByTagName('p');
        // for(var i=0;i<ps.length;i++){
        // ps[i].style.fontSize=size +'px';
        // }
        //
        // }
        // </script>
    }

    /**
     * 适配字体大小
     *
     * @param textSize
     * @return
     */
    public static int getFontSize(int textSize) {
        int rate = (int) (textSize * (float) AppConfig.getScreenHeight() / 940);
        return rate;
    }

    public static int textFontSize(int textSize) {
        int rate = (int) (textSize * (float) AppConfig.getScreenDensityDpi());
        return rate;
    }

    /*
     * 调用系统发送短信
     *
     * @param msg 短信内容
     *
     * @param c
     */
    public static void sendMessageInfo(String who, String msg, Context c) {
        Uri uri = Uri.parse("smsto:" + who);
        Intent it = new Intent(Intent.ACTION_SENDTO, uri);
        it.putExtra("sms_body", msg);
        c.startActivity(it);

    }

    public static String replacePhone(String phone) {
        Pattern p = Pattern.compile("(\\d{3})\\d+(\\d{4})");
        Matcher m = p.matcher(phone);
        if (m.find()) {
            phone = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
            return phone;
        } else {
            return phone;
        }
    }

    /**
     * 判断activity是否运行
     *
     * @param mContext
     * @param activityClassName
     * @return
     */
    public static boolean isActivityRunning(Context mContext, String activityClassName) {
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> info = activityManager.getRunningTasks(1);
        if (info != null && info.size() > 0) {
            for (int i = 0; i < info.size(); i++) {
                ComponentName component = info.get(i).baseActivity;
                if (activityClassName.equals(component.getClassName())) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void callPhone(Context c, String tel) {
        // Intent phoneIntent = new Intent("android.intent.action.CALL",
        // Uri.parse("tel:" + tel));//直接拨打电话
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));// 拨打电话的界面
        // 启动
        c.startActivity(intent);
    }

    public static SpannableStringBuilder textViewColor(Context c, String str, int color, int start, int end) {
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        style.setSpan(new ForegroundColorSpan(c.getResources().getColor(color)), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        return style;
    }

    public static Spannable textViewColorAndBold(Context c, String str, int color, int start, int end, int size) {
        Spannable WordtoSpan = new SpannableString(str);
        WordtoSpan.setSpan(new AbsoluteSizeSpan(c.getResources().getDimensionPixelOffset(size), true), start, end,
                Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        WordtoSpan.setSpan(new ForegroundColorSpan(c.getResources().getColor(color)), start, end,
                Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        return WordtoSpan;
    }

    public static SpannableStringBuilder textViewBold(Context c, String str, int color, int start, int end) {
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
        style.setSpan(new ForegroundColorSpan(c.getResources().getColor(color)), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        style.setSpan(bss, start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        return style;
    }

    public static boolean getHost(String url) {
        if (url.contains("http://") || url.contains("https://")) {
            return true;
        }
        return false;
    }

    public static String fullUrl(String url) {
        if (!getHost(url)) {
            url = HttpUrls.PRIMARY_URL + url;
        }
        return url;
    }

    public static String ImageUrl(String url) {
        if (!getHost(url)) {
            url = "http://hlzy.ppxlm666.com" + url;
        }
        return url;
    }

    /**
     * @param h高度
     * @param w宽度
     * @return
     */
    public static int imgScreenScale(int h, int w) {
        float ww = AppConfig.getScreenWidth();
        float wa = ww / w;// 宽度比
        float ha = h * wa;
        return (int) ha;
    }

    /**
     * 获取webview的里面图片的url
     *
     * @param content
     */
    public static List<String> getWebViewImgUrl(String content) {
        List<String> pic = new ArrayList<String>();
        String regEx = "<img.+?src=['\"](.+?)['\"].+?\\/?>";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(content);
        while (matcher.find()) {
            String temp = matcher.group(1);
            pic.add(temp);
        }
        return pic;
    }

    public static String formatStringZero(String str) {
        if (StringUtil.isEmptyString(str)) {
            return "";
        }
        if (str.indexOf(".") > 0) {
            // 正则表达
            str = str.replaceAll("0+?$", "");// 去掉后面无用的零
            str = str.replaceAll("[.]$", "");// 如小数点后面全是零则去掉小数点
        }
        return str;
    }

    /**
     * 去掉字符串的html标签
     *
     * @param html
     * @return
     */
    public static String replaceStringHtml(String html) {
        if (StringUtil.isEmptyString(html)) {
            return html;
        }
        return html = html.replaceAll("<.+?>", "").replaceAll("\n|\r|\t", "").replaceAll("&nbsp", "");
    }

    public static String deleteStringHtml(String html) {
        if (StringUtil.isEmptyString(html)) {
            return html;
        }
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
        String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符
        return html = html.replaceAll(regEx_script, "").replaceAll(regEx_style, "").replaceAll(regEx_html, "")
                .replaceAll(regEx_space, "").replaceAll("&nbsp", "");
    }

    /**
     * 去掉字符串的UBB标签
     *
     * @param html
     * @return
     */
    public static String replaceStringUbb(String html) {
        if (StringUtil.isEmptyString(html)) {
            return html;
        }
        return html = html.replaceAll("\\[[^\\]]+\\]", "");
    }

    /**
     * 论坛评论去掉字符串的UBB标签包括内容
     *
     * @param html
     * @return
     */
    public static String replaceStringUbbAndContent(String html) {
        if (StringUtil.isEmptyString(html)) {
            return html;
        }
        return html = html.replaceAll("\\[quote\\].+?\\[/quote\\]", "");
    }

    public static void startTypeActivity(int type, String param, Context c, boolean ispush) {
//		Intent in = new Intent();
//		AppAdvertEnum ad = AppAdvertEnum.getEnum(type);
//		if (ad == null) {
//			ad = AppAdvertEnum.getEnum(0);
//		}
//		switch (ad) {
//		case None:
//			in.setClass(c, MainActivity.class);
//			break;
//		case Web:
//			in.putExtra("id", param);
//			in.setClass(c, JxNewsNlWebActivity.class);
//			break;
//		case Activity:
//			in.putExtra("type", 2);
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.setClass(c, ActivityTourismDetailActivity.class);
//			}
//			break;
//		case News:
//			in.putExtra("type", 1);
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.setClass(c, NewsDetailActivty.class);
//			}
//			break;
//		case Politics:
//			in.putExtra("type", 0);
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.setClass(c, WzDetailActivty.class);
//			}
//			break;
//		case BBS:
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.setClass(c, BBsDetailActivity.class);
//			}
//			break;
//		case HotNews:
//			//
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.setClass(c, NewsDetailActivty.class);
//			}
//			break;
//		case LineNews:
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.putExtra("type", 3);
//				in.setClass(c, NewsDetailActivty.class);
//			}
//			break;
//		case SharpNews:
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.setClass(c, NewsDetailActivty.class);
//			}
//			break;
//		case TopNews:
//			if (StringUtil.isEmptyString(param)) {
//				in.putExtra("postion", ad.getIndex());
//				in.setClass(c, MainActivity.class);
//			} else {
//				in.putExtra("id", Integer.valueOf(param));
//				in.setClass(c, NewsDetailActivty.class);
//			}
//			break;
//		case Video:
//			in.putExtra("postion", ad.getIndex());
//			in.setClass(c, MainActivity.class);
//			break;
//		case Vote:
//			in.putExtra("id", Integer.valueOf(param));
//			in.setClass(c, ActivityVoteActivity.class);
//			break;
//
//		default:
//			in.setClass(c, MainActivity.class);
//			in.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//		}
//		if (in.getComponent() == null) {
//			// 没有设置class
//			if (!ispush) {
//				return;
//			}
//			in.setClass(c, MainActivity.class);
//			in.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//		}
//		in.putExtra("push", ispush);
//		in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		c.startActivity(in);
    }

    public static int getCurrentMoth() {
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH);
        return month+1;
    }

    public static int getCurrentYear() {
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.YEAR);
        return month;
    }

    /**
     * 隐藏虚拟键盘
     *
     * @param v
     */
    public static void HideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);

        }
    }

    /**
     * 获取文件名
     *
     * @param fName
     * @return
     */
    public static String getFileName(String fName) {
        if (StringUtil.isEmptyString(fName)) {
            return "";
        }
        File tempFile = new File(fName.trim());
        String fileName = tempFile.getName();
        return fileName;
    }

    // 安装下载后的apk文件
    public static void Instanll(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        ThisAppApplication.getInstance().getApplicationContext().startActivity(intent);
    }

    /**
     * @param imgh         图片高度
     * @param imgw         图片宽度
     * @param screenWeight 屏幕分及等分
     * @param imgWeight    图片占屏幕及等分
     * @return返回图片的高宽
     */
    public static int[] imgScreenHeightScale(int imgh, int imgw, int screenWeight, int imgWeight) {
        float hh = AppConfig.getScreenHeight() / screenWeight * imgWeight;
        float ha = hh / imgh;// 宽度比
        float wa = imgw * ha;
        return new int[]{(int) hh, (int) wa};
    }

    /**
     * @param nowtime    ,现在的时间，或者匹配相对这个时间
     * @param time       ，需要匹配的时间
     * @param timeFormat ，匹配时间的格式
     * @return
     */
    public static boolean expiredTime(String nowtime, String time, String timeFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
        try {
            Date d = sdf.parse(time);
            Date now = sdf.parse(nowtime);
            return d.before(now);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 分割List
     *
     * @param list     待分割的list
     * @param pageSize 每段list的大小
     * @return List<< List < T>>
     * @author bianrx
     */
    public static <T> List<List<T>> splitList(List<T> list, int pageSize) {

        int listSize = list.size(); // list的大小
        int page = (listSize + (pageSize - 1)) / pageSize; // 页数
        List<List<T>> listArray = new ArrayList<List<T>>(); // 创建list数组
        // ,用来保存分割后的list
        for (int i = 0; i < page; i++) { // 按照数组大小遍历
            List<T> subList = new ArrayList<T>(); // 数组每一位放入一个分割后的list
            for (int j = 0; j < listSize; j++) { // 遍历待分割的list
                int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize; // 当前记录的页码(第几页)
                if (pageIndex == (i + 1)) { // 当前记录的页码等于要放入的页码时
                    subList.add(list.get(j)); // 放入list中的元素到分割后的list(subList)
                }

                if ((j + 1) == ((j + 1) * pageSize)) { // 当放满一页时退出当前循环
                    break;
                }
            }
            listArray.add(subList); // 将分割后的list放入对应的数组的位中
        }
        return listArray;
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filePath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        boolean flag = false;
        // 如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        // 遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                // 删除子文件
                flag = files[i].delete();
                if (!flag)
                    break;
            } else {
                // 删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        // 删除当前空目录
        return dirFile.delete();
    }

    /**
     * 根据用户生日计算年龄
     */
    public static int getAgeByBirthday(String birthday) {

        Date year = getFormatDate(birthday);
        if (year == null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                year = sdf.parse(birthday);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday)) {
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(year);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        }
        return age;
    }

    public static void setTextViewCenterLine(TextView txt) {
        txt.getPaint().setAntiAlias(true);// 抗锯齿
        txt.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
    }

    public static void startWebView(String url, BaseActivity<?> ac) {
        if (StringUtil.isEmptyString(url)) {
            return;
        }
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        ac.startMyActivity(intent);
    }

    /**
     * 判断是否有虚拟键盘
     *
     * @param ac
     * @return
     */
    public static int getNavigationBarHeight(BaseActivity<?> ac) {
        Resources resources = ac.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            int height = resources.getDimensionPixelSize(resourceId);
            return height;
        }
        return 0;
        // boolean hasMenuKey = ViewConfiguration.get(ac).hasPermanentMenuKey();
        // boolean hasBackKey =
        // KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
        // if (!hasMenuKey && !hasBackKey) {
        // Resources resources =
        // ThisAppApplication.getInstance().getResources();
        // int resourceId = resources.getIdentifier("navigation_bar_height",
        // "dimen", "android");
        // // 获取NavigationBar的高度
        // int height = resources.getDimensionPixelSize(resourceId);
        // return height;
        // } else {
        // return 0;
        // }
    }

    /**
     * @param v
     * @param h          图片的原始高度
     * @param w          图片的原始宽度
     * @param viewWeight view需要显示的宽度
     */
    public static void setViewLayoutViewHeight(View v, int h, int w, int viewWeight) {
        float wa = viewWeight / (float) w;// 宽度比
        float ha = h * wa;
        v.getLayoutParams().width = (int) viewWeight;
        v.getLayoutParams().height = (int) ha;
    }

    public static void setViewLayoutViewHeight(View v, float h, float w, int viewWeight) {
        float wa = viewWeight / (float) w;// 宽度比
        float ha = h * wa;
        v.getLayoutParams().width = (int) viewWeight;
        v.getLayoutParams().height = (int) ha;
    }

    /**
     * @param weg     html的标签，比如img
     * @param sty     比如img的高宽字符串
     * @param replace 比如把高宽字符串后面的数字替换成这个字符
     * @param html    html内容
     * @return
     */
    public static String replaceHtmlStyle(String weg, String sty, String replace, String html) {
        String regEx = "(\\<" + weg + ".+?" + sty + "\\=\").+?(\".+?>)"; //
        // String regEx = "(<"+weg+"[^>]+"+sty+"=\")(\\S+)\""; //
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(html);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(result, matcher.group(1) + replace + matcher.group(2));
        }
        matcher.appendTail(result);
        return result.toString();
    }

    public static String getObjectFieldName(Object obj) {
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        try {
            for (Field field : obj.getClass().getFields()) {
                String name = field.getName();
                parameters.put(name, field.get(obj));
            }
        } catch (Exception e) {
            System.out.println("--" + e);
        }
        String key = "huanlezhuangyuan20200528@year";
        String characterEncoding = "UTF-8";         //指定字符集UTF-8
        return createSign(characterEncoding, parameters, key);
    }

    public static String getObjectFieldName(SortedMap<Object, Object> parameters) {
//        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
//        try {
//            for (Field field : obj.getClass().getFields()) {
//                String name = field.getName();
//                parameters.put(name, field.get(obj));
//            }
//        } catch (Exception e) {
//            System.out.println("--"+e);
//        }
        String key = "huanlezhuangyuan20200528@year";
        String characterEncoding = "UTF-8";         //指定字符集UTF-8
        return createSign(characterEncoding, parameters, key);
    }

    public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sbkey = new StringBuffer();
        Set es = parameters.entrySet();  //所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
                sbkey.append(k + "=" + v + "&");
            }
        }
        //System.out.println("字符串:"+sb.toString());
        sbkey = sbkey.append("token=" + key);
        System.out.println("字符串:" + sbkey.toString());
        //MD5加密,结果转换为大写字符
        return MD5Util.MD5Encode(sbkey.toString(), characterEncoding).toUpperCase();
    }

    public static String getTime(int second) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        String hms = formatter.format(second);
        return hms;
    }

    public static int getCurrentAmPm() {
        long time = System.currentTimeMillis();
        final Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(time);
        int hour = mCalendar.get(Calendar.HOUR);
        int apm = mCalendar.get(Calendar.AM_PM);//apm=0 表示上午2113，apm=1表示下午。
        return apm;
    }

    public static boolean isAccessibilityEnabled(Context context) throws RuntimeException {
        if (context == null) {
            return false;
        }

        // 检查AccessibilityService是否开启
        AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        boolean isAccessibilityEnabled_flag = am.isEnabled();

        boolean isExploreByTouchEnabled_flag = false;

        // 检查无障碍服务是否以语音播报的方式开启
        isExploreByTouchEnabled_flag = isScreenReaderActive(context);

        return (isAccessibilityEnabled_flag && isExploreByTouchEnabled_flag);

    }

    private final static String SCREEN_READER_INTENT_ACTION = "android.accessibilityservice.AccessibilityService";
    private final static String SCREEN_READER_INTENT_CATEGORY = "android.accessibilityservice.category.FEEDBACK_SPOKEN";

    public static boolean isScreenReaderActive(Context context) {

        // 通过Intent方式判断是否存在以语音播报方式提供服务的Service，还需要判断开启状态
        Intent screenReaderIntent = new Intent(SCREEN_READER_INTENT_ACTION);
        screenReaderIntent.addCategory(SCREEN_READER_INTENT_CATEGORY);
        List<ResolveInfo> screenReaders = context.getPackageManager().queryIntentServices(screenReaderIntent, 0);
        // 如果没有，返回false
        if (screenReaders == null || screenReaders.size() <= 0) {
            return false;
        }

        boolean hasActiveScreenReader = false;
        if (Build.VERSION.SDK_INT <= 15) {
            ContentResolver cr = context.getContentResolver();
            Cursor cursor = null;
            int status = 0;

            for (ResolveInfo screenReader : screenReaders) {
                cursor = cr.query(Uri.parse("content://" + screenReader.serviceInfo.packageName
                        + ".providers.StatusProvider"), null, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    status = cursor.getInt(0);
                    cursor.close();
                    // 状态1为开启状态，直接返回true即可
                    if (status == 1) {
                        return true;
                    }
                }
            }
        } else if (Build.VERSION.SDK_INT >= 26) {
            // 高版本可以直接判断服务是否处于开启状态
            for (ResolveInfo screenReader : screenReaders) {
                hasActiveScreenReader |= isAccessibilitySettingsOn(context, screenReader.serviceInfo.packageName + "/" + screenReader.serviceInfo.name);
            }

        } else {
            // 判断正在运行的Service里有没有上述存在的Service
            List<String> runningServices = new ArrayList<String>();

            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                runningServices.add(service.service.getPackageName());
            }

            for (ResolveInfo screenReader : screenReaders) {
                if (runningServices.contains(screenReader.serviceInfo.packageName)) {
                    hasActiveScreenReader |= true;
                }
            }
        }

        return hasActiveScreenReader;
    }

    // To check if service is enabled
    public static boolean isAccessibilitySettingsOn(Context context, String service) {

        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        String settingValue = Settings.Secure.getString(
                context.getApplicationContext().getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (settingValue != null) {
            mStringColonSplitter.setString(settingValue);
            while (mStringColonSplitter.hasNext()) {
                String accessibilityService = mStringColonSplitter.next();
                if (accessibilityService.equalsIgnoreCase(service)) {
                    return true;
                }
            }
        }

        return false;
    }

    public static double doubleFormat(double f) {
        BigDecimal b = new BigDecimal(f);
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * Is rooted boolean.
     *
     * @return the boolean
     */
    public static boolean isRooted() {
        // nexus 5x "/su/bin/"
        String[] paths = {"/system/xbin/", "/system/bin/", "/system/sbin/", "/sbin/", "/vendor/bin/", "/su/bin/"};
        try {
            for (int i = 0; i < paths.length; i++) {
                String path = paths[i] + "su";
                if (new File(path).exists()) {
                    String execResult = exec(new String[]{"ls", "-l", path});
                    Log.d("cyb", "isRooted=" + execResult);
                    if (TextUtils.isEmpty(execResult) || execResult.indexOf("root") == execResult.lastIndexOf("root")) {
                        return false;
                    }
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static String exec(String[] exec) {
        String ret = "";
        ProcessBuilder processBuilder = new ProcessBuilder(exec);
        try {
            Process process = processBuilder.start();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                ret += line;
            }
            process.getInputStream().close();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static String[] getLeftTimeFormatedStrings(long leftTime) {
        String days = "00";
        String hours = "00";
        String minutes = "00";
        String seconds = "00";
        String millisSeconds = "000";

        if (leftTime > 0) {
            //毫秒
            long millisValue = leftTime % 1000;
            if (millisValue > 100) {
                millisSeconds = String.valueOf(
                        millisValue);
            } else if (millisValue >= 10 && millisValue < 100) {
                millisSeconds = String.valueOf("0" + millisValue);
            } else {
                millisSeconds = String.valueOf("00" + millisValue);
            }

            //实际多少秒
            long trueSeconds = leftTime / 1000;
            //当前的秒
            long secondValue = trueSeconds % 60;
            if (secondValue < 10) {
                seconds = String.valueOf("0" + secondValue);
            } else {
                seconds = String.valueOf(secondValue);
            }

            //当前的分
            long trueMinutes = trueSeconds / 60;
            long minuteValue = trueMinutes % 60;
            if (minuteValue < 10) {
                minutes = String.valueOf("0" + minuteValue);
            } else {
                minutes = String.valueOf(minuteValue);
            }


            //当前的小时数
            long trueHours = trueMinutes / 60;
            long hourValue = trueHours % 24;
            if (hourValue < 10) {
                hours = String.valueOf("0" + hourValue);
            } else {
                hours = String.valueOf(hourValue);
            }

            //当前的天数
            long dayValue = trueHours / 24;
            if (dayValue < 10) {
                days = String.valueOf("0" + dayValue);
            } else {
                days = String.valueOf(dayValue);
            }
        }
        return new String[]{days, hours, minutes, seconds, millisSeconds};
    }

    public static FrameLayout.LayoutParams getUnifiedBannerLayoutParams(Activity context) {
        Point screenSize = new Point();
        context.getWindowManager().getDefaultDisplay().getSize(screenSize);
        return new FrameLayout.LayoutParams(screenSize.x, Math.round(screenSize.x / 6.4F));
    }

    /**
     * 获取当月的 天数
     */
    public static int getCurrentMonthDay() {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 根据年 月 获取对应的月份 天数
     */
    public static int getDaysByYearMonth(int year, int month) {

        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 设置的需要判断的时间  //格式如2012-09-08
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
//  String pTime = "2012-03-12";
        public  static int getWeek(String pTime, String fm) {
//        String Week = "";
//
        SimpleDateFormat format;
        if (StringUtil.isEmptyString(fm)) {
            format = new SimpleDateFormat("yyyy-MM-dd");
        } else {
            format = new SimpleDateFormat(fm);
        }
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
//            Week += "天";
//        }
//        if (c.get(Calendar.DAY_OF_WEEK) == 2) {
//            Week += "一";
//        }
//        if (c.get(Calendar.DAY_OF_WEEK) == 3) {
//            Week += "二";
//        }
//        if (c.get(Calendar.DAY_OF_WEEK) == 4) {
//            Week += "三";
//        }
//        if (c.get(Calendar.DAY_OF_WEEK) == 5) {
//            Week += "四";
//        }
//        if (c.get(Calendar.DAY_OF_WEEK) == 6) {
//            Week += "五";
//        }
//        if (c.get(Calendar.DAY_OF_WEEK) == 7) {
//            Week += "六";
//        }
        return c.get(Calendar.DAY_OF_WEEK);
    }
    /**
     * 将View从父控件中移除
     */
    public static void removeViewFormParent(View v) {
        if (v == null) return;
        ViewParent parent = v.getParent();
        if (parent instanceof FrameLayout) {
            ((FrameLayout) parent).removeView(v);
        }
    }
}
